package com.eksboot;

/**
 * HexUtils
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-04-26 14:48
 * @blame Team
 */
public class HexUtils {

    private static final char[] HEX_CHAR = {
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * byte[] to hex string
     *
     * @param bytes
     * @return
     */
    public static String byteArrayToHex(byte[] bytes) {
        char[] buf = new char[bytes.length * 2];
        int index = 0;
        // 利用位运算进行转换
        for(byte b : bytes) {
            buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
            buf[index++] = HEX_CHAR[b & 0xf];
        }
        return new String(buf);
    }

    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] hexToByteArray(String str) {
        if(str == null || str.trim().length() == 0) {
            return new byte[0];
        }
        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }
        return bytes;
    }

    public static void main(String[] args) {
        String str = "0aze中文sk";
        String hex = HexUtils.byteArrayToHex(str.getBytes());
        System.out.println(hex);
        System.out.println(new String(HexUtils.hexToByteArray(hex)));

        int i = 0x61;
        System.out.println(new String(HexUtils.hexToByteArray(Integer.toHexString(i))));

    }
}
